package com.diy.sigmund.diyuser.test.controller;

import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.DynamicThreadPoolManager;
import com.diy.sigmund.diycommon.spring.config.dynamicthreadpool.ThreadPoolMonitor;
import com.diy.sigmund.diycommon.util.seq.SeqUtil;
import com.diy.sigmund.diyuser.entity.po.TestSql;
import com.diy.sigmund.diyuser.mapper.service.impl.TestSqlServiceImpl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ylm-sigmund
 * @since 2023/4/20 19:01
 */
@RestController
@RequestMapping("/my")
public class ExcelExportControllerTwo {

    @Autowired
    private TestSqlServiceImpl testSqlService;
    @Autowired
    private DynamicThreadPoolManager dynamicThreadPoolManager;

    @PostMapping(value = "/excel/import")
    public String importExcel(@RequestParam(name = "file") MultipartFile file) throws IOException {
        testSqlService.importExcel(file);
        return "导入成功";
    }

    /** 101万数据，耗时为:171255毫秒 */
    @PostMapping(value = "/excel/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        testSqlService.exportExcel(response);
    }

    /** 多线程批量插入数据 */
    @PostMapping(value = "/excel/saveBatch")
    public void saveBatch() {
        ThreadPoolMonitor executor = dynamicThreadPoolManager.getThreadPoolExecutorMap().get("testDynamicThreadPool-1");
        int n = 50;
        CompletableFuture[] arr = new CompletableFuture[n];
        for (int i = 0; i < n; i++) {
            extracted(executor, arr, i);
        }
        CompletableFuture.allOf(arr).join();
    }

    private void extracted(ThreadPoolMonitor executor, CompletableFuture[] arr, int j) {
        Date date = new Date();
        List<TestSql> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            TestSql testSql = new TestSql();
            testSql.setId(SeqUtil.snowflakeId());
            testSql.setName("四年级学生" + 12);
            testSql.setCreateTime(date);
            testSql.setUpdateTime(date);
            testSql.setDescription("四年级学生" + 13);
            testSql.setSss(date);
            testSql.setA(12);
            testSql.setB(Integer.MAX_VALUE);
            list.add(testSql);
        }
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            testSqlService.saveBatch(list);
            System.out.println("saveBatch success ");
        }, executor);
        arr[j] = future;
    }
}
